import cv2
import numpy as np

drawing = False
mode = True
ix, iy = -1, -1


def call_back_draw(event, x, y, flags, param):
    global drawing, mode, ix, iy

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing == True:
            # mode为true画矩形，要不就画圆
            if mode == True:
                cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2)
            else:
                cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False


img = np.ones((600, 600, 3), np.uint8) * 50
cv2.namedWindow('image')
cv2.setMouseCallback('image', call_back_draw)

while True:
    cv2.imshow('image', img)
    if cv2.waitKey(1) == ord('m'):
        mode = not mode
    elif cv2.waitKey(1) == ord('q'):
        break


cv2.destroyAllWindows()